package com.cloud.rabbitmq.test.direct;

import com.cloud.rabbitmq.test.ConnectionUtil;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;

import java.io.IOException;

/**
 * 生产者，模拟为商品服务
 */
public class Send {
    private final static String EXCHANGE_NAME = "direct_exchange_test";

    public static void main(String[] argv) throws Exception {
        // 获取到连接
        Connection connection = ConnectionUtil.getConnection();
        // 获取通道
        Channel channel = connection.createChannel();
        // 声明exchange，指定类型为direct
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 消息内容
        String message = "商品删除了， id = 1001";
        //发送者通道确认，
//        channel.confirmSelect();//启动发送者通道确认
//        channel.addConfirmListener(new ConfirmListener() {
//            @Override
//            public void handleAck(long deliveryTag, boolean multiple) throws IOException { //只要将消息发送到Exchange上就会回调确认ack,即使路由失败也能回调
//                System.out.println(deliveryTag);
//                System.out.println(multiple);
//                System.out.println("action is success");
//            }
//
//            @Override
//            public void handleNack(long deliveryTag, boolean multiple) throws IOException {//消息丢失才会回调此方法，发送到错误的exchange上不会回调
//                System.out.println(deliveryTag);
//                System.out.println(multiple);
//                System.out.println("action is failed");
//            }
//        });
//        channel.addReturnListener(( replyCode,  replyText,  exchange,  routingKey,  //消息路由失败才会回调此方法，发送到错误的exchange上不会回调
//                                    properties, body)->{
//            System.out.println(replyCode);
//            System.out.println(replyText);
//            System.out.println(exchange);
//            System.out.println(routingKey);
//            System.out.println(properties);
//            System.out.println(body);
//        });


        // 发送消息，并且指定routing key 为：insert ,代表新增商品
        channel.basicPublish(EXCHANGE_NAME, "delete", null, message.getBytes());
        System.out.println(" [商品服务：] Sent '" + message + "'");

        channel.close();
        connection.close();
    }
}
